package com.linkdood.app.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.linkdood.app.constants.ErrorCode;
import com.linkdood.app.exception.GeneralException;
import com.linkdood.app.service.HsgService;
import com.linkdood.app.service.TokenService;
import com.linkdood.app.utils.HttpUtil;
import com.linkdood.app.vm.OrganizationCommunityVm;
import com.linkdood.app.vm.UserVM;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 该类封装了所有和 DDIO 交互的操作
 * 其他地方如果要使用 DDIO 相关的 API 必须通过该类来进行
 *
 * @author lxy
 */
@Slf4j
@Service
public class HsgServiceImpl implements HsgService {

    @Value("${hsg.url}")
    private String hsgUrl;

    /**
     * 调用示例 好家好社区接口 url
     */
    private static final String ORGANIZATION_RANGE = "/api/unified/organizations/range";

    private final TokenService tokenService;

    public HsgServiceImpl(TokenService tokenService) {
        this.tokenService = tokenService;
    }


    /**
     * 获取好社工平台包含 access_token 的消息头
     */
    private HttpHeaders getHttpHeader(String token) {
        if (token != null) {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", token);
            return headers;
        } else {
            return new HttpHeaders();
        }
    }

    /**
     * 调用好家好社区接口文档 3.2.1 获取组织架构列表接口
     */
    @Override
    public List<OrganizationCommunityVm> listOrganizationCommunityByDistance(String coordinate, Integer distance) {
        String url = hsgUrl + ORGANIZATION_RANGE + "?coordinate=" + coordinate + "&distance=" + distance;
        ResponseEntity<String> responseEntityData = HttpUtil.getRestTemplate(url, getHttpHeader(tokenService.hsgToken()));
        if (responseEntityData.getStatusCode() != HttpStatus.OK) {
            log.error("getRoleByUserId error, StatusCode = {}", responseEntityData.getStatusCodeValue());
            throw new GeneralException(ErrorCode.ERROR_UNKNOWN_THIRD_PARTY_PLATFORM);
        } else {
            return JSONArray.parseArray(responseEntityData.getBody(), OrganizationCommunityVm.class);
        }
    }
}
